
from datetime import datetime
from threading import Thread

from blinker import signal
from flask import Blueprint, render_template, request, session, redirect, url_for, flash

# 创建蓝图对象
from flask_login import login_user, login_required, logout_user
from flask_mail import Mail, Message

from form.login_form import LoginForm
from models import User, db

user = Blueprint('myuser', __name__)
mail = Mail()
# 创建信号
signal = signal("view")


# 使用蓝图路由
@user.route('/info/')
def get_info():
    execute = db.session.execute("select * from `user` where name={NAME}".format(NAME="'侯小征'"))
    print(execute.fetchone())
    return {"name": "Jack"}


# 返回模板
@user.route('/get/all/')
def get_all_user():
    title = "  姓名  "
    users = ["姚振", "侯征", "何毅"]
    # 必须以key-value形式返回,模板才会识别对应变量名
    return render_template('user.html', title=title, users=users, curret_data=datetime.now())


# 返回模板
@user.route('/get/child/')
def get_child():
    return render_template('child.html')


@user.route('/get/boot/')
def get_boot():
    return render_template('boot.html')


@user.route('/getuser/<int:id>/')
def get_user(id):
    return User.query.filter_by(id=id).first()


@user.route('/sendmail/')
def send_mail():
    # 设置主题,发送接受人
    msg = Message(subject="Hello World!",
                  sender="799827577@qq.com",
                  recipients=["799827577hou@gmail.com"])
    # 添加内容
    # 邮件内容会以文本和html两种格式呈现，而你能看到哪种格式取决于你的邮件客户端
    msg.body = "测试"
    msg.html = "<h2>测试邮件</h2>"
    mail.send(msg)  # 发送
    return {"result": "ok"}


@user.route('/sendsync/')
def send_sync_mail():
    msg = Message(subject="Hello World!",
                  sender="799827577@qq.com",
                  recipients=["799827577hou@gmail.com"])
    msg.body = "测试异步发送"
    msg.html = "<h2>测试异步发送</h2>"
    thr = Thread(target=signal.send, args=[msg,])
    thr.start()
    return "ok"

@user.route('/login/', methods=['GET', 'POST'])
def login():
    form = LoginForm()  # 实例化form对象
    if request.method == "POST" and form.validate_on_submit():
        username = request.form.get('username')
        password = request.form.get('password')
        user = User.query.filter_by(name=username, password=password).first()
        if user:
            # 将用户信息注册到flask-login中
            login_user(user)
            return redirect(url_for('myuser.get_all_user'))
        else:
            flash("请重新输入用户名和密码")
    return render_template('login.html', form=form)
# @user.route('/login/', methods=['GET', 'POST'])
# def login():
#     form = LoginForm()  # 实例化form对象
#     if form.validate_on_submit():  # 数据正确 并且验证csrf通过,只有POST才会验证
#         # 发送flash消息提醒用户
#         old_name = session.get('username')
#         if old_name is not None and old_name != form.username.data:
#             flash('您输入的用户名改变了!')
#         session['username'] = form.username.data  # 将username保存到session
#         session['password'] = form.username.data
#         return redirect(url_for('user.handle_login'))  # 重定向到函数
#     return render_template('login.html', form=form)


# 使用重定向避免刷新页面表单重复提交
# @user.route('/handle/login')
# def handle_login():
#     print(session['username'])   # 保存到session之后,刷新页面照样可以获取数据,保持在登录成功页面
#     print(session['password'])
#     return "登录成功"
@user.route('/logout/', methods=['GET', 'POST'])
@login_required   # 装饰器,必须登录才能有权限
def logout():
    logout_user()
    return redirect(url_for('myuser.get_all_user'))
